package com.ayf.payment.game.api.channel.ayb.handler;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.channel.ayb.request.AybUserTransferOrderCreateReq;
import com.ayf.payment.game.api.channel.ayb.request.AybUserTransferOrderQueryReq;
import com.ayf.payment.game.api.channel.ayb.response.AybGetChannelBindInfoRes;
import com.ayf.payment.game.api.channel.ayb.response.AybUserTransferOrderCreateRes;
import com.ayf.payment.game.api.channel.ayb.response.AybUserTransferOrderQueryRes;
import com.ayf.payment.game.api.channel.ayb.util.AyUserTransferUtil;
import com.ayf.payment.game.api.entity.ayb.aybUserTransferBind;
import com.ayf.payment.game.api.service.ayb.AybUserTransferBindService;
import com.ayf.payment.game.api.type.MerchantPayOrderStatusEnum;
import com.ayf.payment.game.api.vo.AybChannelConfigVO;
import com.swwx.charm.commons.lang.utils.BeanConvertUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.SocketTimeoutException;

@Component
@Slf4j
public class AybUserTransferHandler {

    private final String aybDomain = System.getenv("AYB_SCAN_CALLBACK_URL");
    private static final String PLATFORM_CODE = System.getenv("GAME_AYFPAY_PLATFORM_CODE");


    //查询绑定信息
    private static final String MERCHANT_CHANNEL_BIND_RESULT = "/ayb-api/p4/merchant/usertransferbind/getBindInfo";
    //创建订单
    private static final String MERCHANT_USER_TRANSFER_ORDER_CREATE = "/ayb-api/p4/merchant/usertransferorder/createOrder";
    //查询订单
    private static final String MERCHANT_USER_TRANSFER_ORDER_GET = "/ayb-api/p4/merchant/usertransferorder/getByMerchantOrder";
    @Autowired
    private AybUserTransferBindService aybUserTransferBindService;

    /**
     * 查询绑定信息
     * @author lch
     * @date 2021/12/10
     */
    public JSONObject getBindInfo(JSONObject inputParam) {
        inputParam.put("platformCode", PLATFORM_CODE);

        JSONObject resJson = new JSONObject();

        String merchantId = inputParam.getString("merchantId");
        String traceId = inputParam.getString("traceId");

        resJson.put("merchantId", merchantId);
        resJson.put("traceId", traceId);
        String url = aybDomain + MERCHANT_CHANNEL_BIND_RESULT;
        try {
            log.info("{} 【查询爱游宝代付绑定信息】请求参数:{}", traceId, inputParam.toJSONString());
            AybGetChannelBindInfoRes res = AyUserTransferUtil.request(traceId, url, inputParam.toJSONString(), null, AybGetChannelBindInfoRes.class);
            resJson.put("aybId", res.getPlayerId());
            resJson.put("publicKey", res.getPublicKey());
            resJson.put("phone", res.getPhone());
            resJson.put("nickName", res.getNickname());
            resJson.put("bindFlag", res.getBindFlag());
        } catch (SocketTimeoutException e) {
            LogPortal.error("{} 【查询爱游宝代付绑定信息】查询 通道响应超时 商户订单号:{}",traceId,merchantId);
        }  catch (Exception e) {
            LogPortal.error("{} 【查询爱游宝代付绑定信息】查询失败，发生{}异常 商户订单号:{}", e, traceId,e.getClass().getName(),merchantId);
        }
        LogPortal.info("{} 【查询爱游宝代付绑定信息】查询 商户订单号:{} 响应报文:{}",traceId,merchantId,resJson.toJSONString());
        return resJson;
    }


    /**
     * 创建代付订单
     * @author lch
     * @date 2021/12/10
     * @param req
     */
    public JSONObject createOrder(AybUserTransferOrderCreateReq req) {
        req.setPlatformCode(PLATFORM_CODE);
        JSONObject resJson = new JSONObject();
        String merchantOrderNo = req.getMerchantOrderNo();
        resJson.put("merchantOrderNo",merchantOrderNo);
        resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());

        String traceId = req.getTraceId();
        Integer merchantId = req.getMerchantId();
        aybUserTransferBind aybUserTransferBind = this.aybUserTransferBindService.getByMerchantId(merchantId);
        AybChannelConfigVO channelConfigVO = BeanConvertUtils.convert(aybUserTransferBind, AybChannelConfigVO.class);
        String url = aybDomain + MERCHANT_USER_TRANSFER_ORDER_CREATE;
        try {
            LogPortal.info("{} 【爱游宝代付下单】请求参数:{}",traceId, JSONObject.toJSONString(req));
            AybUserTransferOrderCreateRes res = AyUserTransferUtil.request(traceId, url, JSONObject.toJSONString(req), channelConfigVO, AybUserTransferOrderCreateRes.class);
            if (res.isReqSuccessFlag()){ // 业务处理成功
                if (res.isSuccess()){ // 业务处理成功
                    resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());
                    resJson.put("channelOrderNo", res.getOrderNo());
                }else {
                    resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
                    resJson.put("failReason", res.getMsg());
                }
            }else {
                resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
                resJson.put("failReason","系统繁忙，请稍后重试");
            }
        } catch (SocketTimeoutException e) {
            LogPortal.error("{} 【爱游宝代付下单】 通道响应超时 商户订单号:{}",traceId,merchantOrderNo);
        } catch (Exception e) {
            LogPortal.error("{} 【爱游宝代付下单】失败，发生{}异常 商户订单号:{}",traceId,e.getClass().getName(),merchantOrderNo);
            resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
            resJson.put("failReason","系统繁忙，请稍后重试");
            return resJson;
        }
        LogPortal.info("{} 【爱游宝代付下单】 商户订单号:{} 响应报文:{}",traceId,merchantOrderNo,resJson.toJSONString());
        return resJson;
    }

    /**
     * 查询代付订单
     * @author lch
     * @date 2021/12/10
     * @param req
     */
    public AybUserTransferOrderQueryRes queryOrder(AybUserTransferOrderQueryReq req) {
        String merchantOrderNo = req.getMerchantOrderNo();

        String traceId = req.getTraceId();
        Integer merchantId = req.getMerchantId();
        aybUserTransferBind aybUserTransferBind = this.aybUserTransferBindService.getByMerchantId(merchantId);
        AybChannelConfigVO channelConfigVO = BeanConvertUtils.convert(aybUserTransferBind, AybChannelConfigVO.class);
        String url = aybDomain + MERCHANT_USER_TRANSFER_ORDER_GET;
        try {
            LogPortal.info("{} 【查询代付订单】请求参数:{}",traceId, JSONObject.toJSONString(req));
            AybUserTransferOrderQueryRes res = AyUserTransferUtil.request(traceId, url, JSONObject.toJSONString(req), channelConfigVO, AybUserTransferOrderQueryRes.class);
            LogPortal.info("{} 【查询代付订单】响应报文:{}",traceId, JSONObject.toJSONString(res));
            if (res.isReqSuccessFlag() && res.isSuccess()){ // 业务处理成功
                return res;
            }
        } catch (SocketTimeoutException e) {
            LogPortal.error("{} 【查询代付订单】 通道响应超时 商户订单号:{}",traceId,merchantOrderNo);
        } catch (Exception e) {
            LogPortal.error("{} 【查询代付订单】失败，发生{}异常 商户订单号:{}",traceId,e.getClass().getName(),merchantOrderNo);
        }
        return null;
    }
}
